<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Db;
use think\facade\Event;

class Admin extends Base
{
    protected function role()
    {
        return $this->hasOne(Role::class, 'id', 'role_id');
    }

    protected function getLastTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '';
    }

    public function login($param)
    {
        try {
            $v = validate('Common');
            if (!$v->scene('login')->check($param)) {
                return json(['code' => -1, 'msg' => $v->getError()]);
            }
            unset($param['captcha']);
            $param['password'] = md5($param['password']);
            $is = $this->where($param)->find();
            if (empty($is)) {
                return json(['code' => -1, 'msg' => '用户名不存在或密码错误']);
            }
            if ($is['is_del'] == 1 || $is['status'] != 1) {
                return json(['code' => -1, 'msg' => '该用户已被删除或已停用']);
            }
            $is->last_time = time();
            $is->save();
            session('admin_id', $is['id']);
            session('password_token', md5($is->password));
            Logs::adds('管理员【' . $is['admin_name'] . '】登录了系统');

        } catch (\Exception $e) {

            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

        return json(['code' => 1, 'msg' => '登录成功']);
    }

    public static function _save($param, $logs): array
    {
        try {
            if (isset($param['id']) && $param['id']) {
                $original = parent::where($logs['pk'], $param[$logs['pk']])->find();
                if (empty($original)) {
                    throw new \Exception('记录不存在，请检查！');
                }
                if (parent::where(['admin_name' => $param['admin_name'], 'is_del' => 0])->where('id', '<>', $param['id'])->count()) {
                    throw new \Exception('用户名已存在');
                }
                $group = Db::name('auth_group_access')->where('uid', $param['id'])->find();
                if ($group['group_id'] != $param['role_id']) {
                    Db::name('auth_group_access')->where('uid', $param['id'])->update(['group_id' => $param['role_id']]);
                }
                $model = parent::update($param);
                $logs['original'] = $original;
                $logs['operation'] = 'save';
                if ($logs['writeLog']) {
                    $logs['model'] = $model;
                    Event::trigger('Logs', $logs);
                }
            } else {
                if (parent::where(['admin_name' => $param['admin_name'], 'is_del' => 0])->count()) {
                    throw new \Exception('用户名已存在');
                }
                $model = parent::create($param);
                Db::name('auth_group_access')->insert(['uid' => $model->id, 'group_id' => $model->role_id]);
                Logs::adds('后台添加新管理员，用户名【' . $model->admin_name . '】');
            }

        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '操作成功'];
    }
}